package com.epalmpay.service.management.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.epalmpay.entity.*;
import com.epalmpay.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.sms.ISMSService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import com.epalmpay.util.Const;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.SendEmailUtil;
import com.epalmpay.util.StringReplaceUtil;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.Tools;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;


@Component("mailSendService") 
@Scope("singleton")
public class TemplateMailSendServiceImpl implements ITemplateMailSendService {

	@Resource
    private ISMSService smsService;
	@Resource
	private ShopUserMapper shopUserMapper;
	@Resource
	private ShopMapper shopMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;
	@Resource
	private OrderServiceGoodMapper orderServiceGoodMapper;
	@Resource
	private OrderGoodItemMapper orderGoodItemMapper;
	@Resource
	private OrderGoodMapper orderGoodMapper;
	@Resource
	private GroupWxtemplateMapper groupWxtemplateMapper;
	@Resource
	private MemberAddressMapper memberAddressMapper;
	@Resource
	protected WxService wxService;
	@Resource
	protected IWxBaseService wxBaseService;

    @Resource
    private IWalletService walletService;

    @Resource
    private MachineWasherLogMapper machineWasherLogMapper;
	
	/**
	 * 使用Async异步处理多线程
	 */
	@Override
	@Async
	public Boolean sendMail(String title,String content,String tomail) throws Exception {
		SendEmailUtil.sendTextMail(title, content,tomail);
		return true;
	}

	
	
	
	@Override
	@Async
	public Boolean sendMerchantCreateSms(Long groupId,String phone,String username,String password) throws Exception {
		//发短信
		Map<String, String> params=new HashMap<String, String>();
		int endIndex = 0;
		endIndex=username.lastIndexOf("@");
		params.put("name",username.substring(0,endIndex)+"的邮箱");
		params.put("key",password);
		try {
			boolean flag=smsService.sendRegionCode(groupId, null, BizEnum.SMSTemplateType.temp_SMS_109545047.getType(), phone, params);
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException(Rescode.FAIL,"短信发送异常");
		}
		
	}


	@Override
	@Async
	public Boolean sendAgentCreateSms(Long groupId,String phone,String username,String password) throws Exception {
		//发短信
		Map<String, String> params=new HashMap<String, String>();
		int endIndex = 0;
		endIndex=username.lastIndexOf("@");
		params.put("name",username.substring(0,endIndex)+"的邮箱");
		params.put("key",password);
		try {
			boolean flag=smsService.sendRegionCode(groupId, null, BizEnum.SMSTemplateType.temp_SMS_109500051.getType(), phone, params);
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException(Rescode.FAIL,"短信发送异常");
		}
		
	}



	@Override
	@Async
	public Boolean sendTemplate(TradeOffline tradeOffline, String template,Long memberId, Long groupId, Integer businessType,String masterUrl) throws Exception {
		 GroupWxtemplate groupWxtemplate = groupWxtemplateMapper.selectByTemplateTypeAndGroup(template, groupId);
		 System.out.println("----------------------------发送模板消息----------"+template);
		if (groupWxtemplate == null||StringUtils.isBlank(groupWxtemplate.getTemplateId())) { 
			return false;
		}
		Member member = memberMapper.queryGroup(memberId);
		if(member==null){
			return false;
		}
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupId));
		
		String url=String.format("%s/"+groupId+"/share_to.html?uid="+memberId,masterUrl);
		
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		 if (BizEnum.WebTemplateType.template2.getType().equals(template)) {// 充值通知
			// 微信充值通知     \n感谢惠顾，点击“详情”分享给您的朋友，将给您带来源源不断收益。
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setToUser(member.getOpenid());
	//		String url=String.format("%s/"+groupId+"/trans_order_details.html?orderId="+tradeOffline.getOrderId()+"&transactionType=3",masterUrl);
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "您好，您已成功进行微信钱包充值。", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("accountType", "会员号:", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("account", member.getPhone(), "#000080"));
			double orderAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
			templateMessage.getData().add(new WxMpTemplateData("amount", orderAmount + "元", "#FF0000"));// 金额
			templateMessage.getData().add(new WxMpTemplateData("result", "充值成功", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		} else if (BizEnum.WebTemplateType.template3.getType().equals(template)) {// 提现通知     如有疑问，请拨打客服热线4000090876。
			//		String url=String.format("%s/"+groupId+"/trans_order_details.html?orderId="+tradeOffline.getOrderId()+"&transactionType=4",masterUrl);
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "您好，您的账户申请提现成功", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword1", tradeOffline.getOrderId(), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword2", DateUtil.getTime(), "#000080"));
			double orderAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
			templateMessage.getData().add(new WxMpTemplateData("keyword3", orderAmount+"元", "#FF0000"));
			templateMessage.getData().add(new WxMpTemplateData("keyword4", 
					"银行卡号" + StringReplaceUtil.bankCardReplaceWithStar(4, tradeOffline.getPayAccount()), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。","#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		} else if (BizEnum.WebTemplateType.template4.getType().equals(template)) {// 订单支付成功
			 String goodName = null;
			 //		 String url=null;
			 if (tradeOffline.getOrderId().startsWith(Const.CONSUMPTION_REAL)) {
				 OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.WaitingForDeliver.getType());
					if(orderGood!=null){
						List<OrderGoodItem> orderGoodItemList=orderGoodItemMapper.listByOrderId(orderGood.getId());
						if(orderGoodItemList.size()==1){
							goodName=orderGoodItemList.get(0).getGoodName();
						}else if(orderGoodItemList.size()>1){
							goodName=orderGoodItemList.get(0).getGoodName()+"等"+orderGoodItemList.size()+"款商品信息";
						}
					}
			//		url=String.format("%s/"+groupId+"/shop_order_detail.html?orderId="+orderGood.getId(),masterUrl);
			 }else if(tradeOffline.getOrderId().startsWith(Const.CONSUMPTION_VIRTUAL)){  
				 OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectOrderServiceGoodInfo(tradeOffline.getOrderId(),
							BizEnum.ServiceOrderStatus.WaitingForUse.getType());
				 goodName = orderServiceGood.getGoodName();
			//	    url=String.format("%s/"+groupId+"/orderdetail.html?orderNum="+tradeOffline.getOrderId(),masterUrl);
			 }
				templateMessage.setUrl(url);
				templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
				templateMessage.setToUser(member.getOpenid());
				templateMessage.getData().add(new WxMpTemplateData("first", "尊敬的用户,您购买的商品已成功支付。", "#000080"));
				double orderAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
				templateMessage.getData().add(new WxMpTemplateData("orderMoneySum", orderAmount + "元", "#FF0000"));// 支付金额
				templateMessage.getData().add(new WxMpTemplateData("orderProductName", goodName, "#000080"));// 商品信息
				templateMessage.getData().add(new WxMpTemplateData("Remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
				wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
				return true;
		} else if (BizEnum.WebTemplateType.template5.getType().equals(template)) {// 退款成功通知
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "您已发起退款成功", "#000080"));
		//	double orderAmount = (double) (Math.round(tradeOffline.getOrderAmount()) / 100.0);
			
			double realAmount=0;
			if (tradeOffline.getOrderId().startsWith(Const.CONSUMPTION_REAL)) {
				OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(tradeOffline.getOrderId(), BizEnum.MallOrderStatus.Refunded.getType());
				realAmount=(double) (Math.round(orderGood.getRefundAmount()) / 100.0);
			}else{
				 realAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
			}
			templateMessage.getData().add(new WxMpTemplateData("keyword1", "退款金额"+realAmount+"元", "#FF0000"));
			templateMessage.getData().add(new WxMpTemplateData("keyword2", "原路退回", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword3", "具体到账时间以收到时间为准", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		} else if (BizEnum.WebTemplateType.template6.getType().equals(template)) {// 获得返现通知
			//		String url=String.format("%s/"+groupId+"/transfer_success.html?orderId="+tradeOffline.getOrderId()+"&transactionType=12",masterUrl);
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "恭喜您，获得返现", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword1", "交易返现", "#000080"));
			double orderAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
			templateMessage.getData().add(new WxMpTemplateData("keyword2", orderAmount + "元", "#FF0000"));
			templateMessage.getData().add(new WxMpTemplateData("keyword3", "钱包支付", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n点击详情可查看交易明细。", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
		}  else if (BizEnum.WebTemplateType.template9.getType().equals(template)) {// 转账通知   
			Member memberInfo=memberMapper.selectByPrimaryKey(Long.valueOf(tradeOffline.getReceiverId()));
			//	String url=String.format("%s/"+groupId+"/transfer_success.html?ordernum="+tradeOffline.getOrderId(),masterUrl);
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "您已成功对"+tradeOffline.getReceiverName()+"进行一笔转帐", "#000080"));
			double orderAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
			templateMessage.getData().add(new WxMpTemplateData("keyword1", orderAmount + "元", "#FF0000"));
			templateMessage.getData().add(new WxMpTemplateData("keyword2", memberInfo.getPhone(), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword3", DateUtil.getTime(), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		} else if (BizEnum.WebTemplateType.template11.getType().equals(template)) {// 会员消费提醒
			// 台卡-pos消费  
				Shop shop = shopMapper.selectByPrimaryKey(Long.valueOf(tradeOffline.getReceiverId()));
				if (shop != null) {
					//				String url=String.format("%s/"+groupId+"/trans_order_details.html?orderId="+tradeOffline.getOrderId()+"&transactionType=1",masterUrl);
					templateMessage.setUrl(url);
					templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
					templateMessage.setToUser(member.getOpenid());
					templateMessage.getData().add(new WxMpTemplateData("first", "尊敬的用户,您已消费成功。", "#000080"));
					templateMessage.getData().add(new WxMpTemplateData("keyword1", member.getPhone(), "#000080"));
					templateMessage.getData().add(new WxMpTemplateData("keyword2", shop.getMerchantName(), "#000080"));// 店铺名称
					double orderAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
					templateMessage.getData().add(new WxMpTemplateData("keyword3", orderAmount + "元", "#FF0000"));// 消费金额
					templateMessage.getData().add(new WxMpTemplateData("remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
					wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
					return true;
			}
		}  else if (BizEnum.WebTemplateType.template13.getType().equals(template)) {
			// http://sbs.eboss007.com/3/trans_order_details.html?orderId=20171201171759&transactionType=9
			//		String url=String.format("%s/"+groupId+"/trans_order_details.html?orderId="+tradeOffline.getOrderId()+"&transactionType="+tradeOffline.getTransactionType(),masterUrl);
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "尊敬的用户,您的账户发生变动", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword1", DateUtil.getTime(), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword2", "个人转账"));
			double orderAmount = (double) (Math.round(tradeOffline.getRealAmount()) / 100.0);
			templateMessage.getData().add(new WxMpTemplateData("keyword3", orderAmount + "元", "#FF0000"));
			String balance = queryAmount(member.getVirtualCard(), member.getPayGroupCode(),member.getUserId());
			Double keyword4 = Double.valueOf(balance) / 100;
			templateMessage.getData().add(new WxMpTemplateData("keyword4", keyword4 + "", "#000080"));// 当前余额
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		} else if (BizEnum.WebTemplateType.template16.getType().equals(template)){//给洗衣机用的服务完成提醒
			 MachineWasherLog machineWasherLog = new MachineWasherLog();
			 machineWasherLog.setOrderno(tradeOffline.getOrderId());
			 Map result = machineWasherLogMapper.selectWasherLogByOrderNo(machineWasherLog);
			 templateMessage.setToUser(member.getOpenid());
			 templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			 templateMessage.setUrl(url);
			 templateMessage.getData().add(new WxMpTemplateData("first", "亲，很高兴为您服务", "#000080"));
			 templateMessage.getData().add(new WxMpTemplateData("keyword1", tradeOffline.getOrderId(), "#000080"));//订单号
			 templateMessage.getData().add(new WxMpTemplateData("keyword2", "您选择了" + BizEnum.WashType.fromType(Integer.parseInt(result.get("washtype").toString())).getName() + "洗衣"));//服务项目
			 templateMessage.getData().add(new WxMpTemplateData("keyword3", result.get("gmt_create").toString(), "#FF0000"));//开始服务时间
			 templateMessage.getData().add(new WxMpTemplateData("keyword4", DateUtil.getTime(), "#000080"));// 完成服务时间
			 templateMessage.getData().add(new WxMpTemplateData("remark", "\n您的洗衣服务2分钟后完成，请记得及时取出晾晒。", "#000080"));
			 wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			 return true;
		 } else if (BizEnum.WebTemplateType.template17.getType().equals(template)) {//给洗衣机用的设备故障提醒
			 MachineWasherLog machineWasherLog = new MachineWasherLog();
			 machineWasherLog.setOrderno(tradeOffline.getOrderId());
			 Map result = machineWasherLogMapper.selectWasherLogByOrderNo(machineWasherLog);
			 templateMessage.setToUser(member.getOpenid());
			 templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			 templateMessage.setUrl(url);
			 templateMessage.getData().add(new WxMpTemplateData("first", "小主，您好!您选用的洗衣机出现故障!", "#000080"));
			 templateMessage.getData().add(new WxMpTemplateData("keyword1", result.get("boardid").toString(), "#000080"));//设备编号
			 templateMessage.getData().add(new WxMpTemplateData("keyword2", result.get("address").toString()));//故障位置
			 templateMessage.getData().add(new WxMpTemplateData("keyword3", DateUtil.getTime(), "#FF0000"));//故障时间
			 templateMessage.getData().add(new WxMpTemplateData("keyword4", BizEnum.WashFaultStatus.fromType(Integer.parseInt(result.get("faultstatus").toString())).getName() + "", "#000080"));//故障内容
			 if("4".equals(result.get("faultstatus").toString())) {
				 templateMessage.getData().add(new WxMpTemplateData("remark", "\n请检查洗衣机门盖是否盖好!确认盖好继续洗衣。谢谢配合!", "#000080"));
			 } else {
				 templateMessage.getData().add(new WxMpTemplateData("remark", "\n请另寻机器洗，给您添麻烦了!", "#000080"));
			 }
			 wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			 return true;
		 }
		return false;
	}

	
	@Override
	@Async
	public Boolean sendMemberTemplate(Long memberId, String template, String masterUrl,String description) throws Exception {
		Member member = memberMapper.selectByPrimaryKey(memberId);
		
		System.out.println("会员id:"+member.getId());
		
		String url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,masterUrl);
		GroupWxtemplate groupWxtemplate = groupWxtemplateMapper.selectByTemplateTypeAndGroup(template, member.getGroupId());
		
		System.out.println("模板id"+groupWxtemplate.getId());
		
		if (groupWxtemplate == null||Tools.isEmpty(groupWxtemplate.getTemplateId())) {
			System.out.println("---------------------------------未查询到模板记录----------------------------");
			return false;
		}
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(member.getGroupId()));
		
		
		
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		if (BizEnum.WebTemplateType.template1.getType().equals(template)) {// 成为会员通知
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			
			templateMessage.getData().add(new WxMpTemplateData("first", "您好，恭喜注册成功。", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword1", member.getWeixinName(), "#000080"));
			
			templateMessage.getData().add(new WxMpTemplateData("keyword2", member.getBonusAmount()+""));// bonus_amount
			templateMessage.getData().add(new WxMpTemplateData("keyword3", SysUtils.formatDate(member.getGmtModified(), "yyyy-MM-dd HH:mm:ss"), "#000080"));
			
			
					if(member.getGroupId()==21L){
						System.out.println("田园模板消息6");
						StringBuffer sb=new StringBuffer();
						sb.append("\t");
						sb.append("恭喜您成为田好大家族的一员，悄悄告诉您个小秘密，现在您可是个有特权的人了哦。不信，那就点击下面链接试试。");
						sb.append("\n");
						sb.append("将商城产品分享给好友，消费成功立刻获得奖励");
						sb.append("\n");
						sb.append("\t");
						sb.append("如果将您的专属二维码分享给第三人，财源更是滚滚来。点击此处进入页面");
						sb.append("\n");
						sb.append("\t");
						sb.append("钱包充值购物，还可享受会员折上折。点击进入【钱包充值】");
						String urls=masterUrl+"/pay/recharge/remain_recharge.html?groupId="+member.getGroupId()+"&memberId="+memberId;
						templateMessage.setUrl(urls);
						templateMessage.getData().add(new WxMpTemplateData("remark", sb.toString(), "#000080"));
					}else{
						templateMessage.setUrl(url);
						templateMessage.getData().add(new WxMpTemplateData("remark", "\n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
					}
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		} else if (BizEnum.WebTemplateType.template7.getType().equals(template)) {// 审核结果通知

			
			
		}else if (BizEnum.WebTemplateType.template14.getType().equals(template)) {// 密码修改通知
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "您好，您的"+description+"密码已修改成功。", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword1", member.getPhone(), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword2", DateUtil.getTime(),"#000080"));
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n如非本人操作，请及时拔打客服热线4000090876。", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		}else if (BizEnum.WebTemplateType.template15.getType().equals(template)) {// 参与成功通知
           
			
			return true;
		}
		return null;
	}
	
	
	@Override
	@Async
	public Boolean sendCouponVerifyTemplate(Long shopId,Long memberId, String couponCode,String goodName,
			String template,String orderNum,String masterUrl) throws Exception {
	  if (BizEnum.WebTemplateType.template8.getType().equals(template)) {// 核销成功提醒
		Member member = memberMapper.selectByPrimaryKey(memberId);
		GroupWxtemplate groupWxtemplate = groupWxtemplateMapper.selectByTemplateTypeAndGroup(template, member.getGroupId());
		if (groupWxtemplate == null||StringUtils.isBlank(groupWxtemplate.getTemplateId())) {
			return false;
		}
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(member.getGroupId()));
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		Shop shop = shopMapper.selectByPrimaryKey(shopId);
		//    String url=String.format("%s/"+member.getGroupId()+"/orderdetail.html?orderNum="+orderNum,masterUrl);
		    String url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,masterUrl);
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "您的卡劵已成功核销", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword1", goodName, "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword2", couponCode, "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword3", DateUtil.getTime(), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword4",  shop.getMerchantName(), "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("remark", " \n感谢惠顾，<点击邀请好友，共享会员超级福利>，给您带来源源不断地收益。", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		}
	  return false;
	}

	
	@Override
	@Async
	public Boolean sendOrderTemplate(String orderId, String template, Long memberId, Long groupId, String masterUrl) throws Exception {
		GroupWxtemplate groupWxtemplate = groupWxtemplateMapper.selectByTemplateTypeAndGroup(template, groupId);
		Member member = memberMapper.selectByPrimaryKey(memberId);
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupId));
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		if (BizEnum.WebTemplateType.template12.getType().equals(template)) {// 订单取消通知
			String goodName = null;
			String orderAddress=null;
			Integer orderProductPrice=null;
			String url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,masterUrl);
			 if (orderId.startsWith(Const.CONSUMPTION_REAL)) {
				 OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(orderId, BizEnum.MallOrderStatus.canceled.getType());
					if(orderGood!=null){
						List<OrderGoodItem> orderGoodItemList=orderGoodItemMapper.listByOrderId(orderGood.getId());
						if(orderGoodItemList.size()==1){
							goodName=orderGoodItemList.get(0).getGoodName();
						}else if(orderGoodItemList.size()>1){
							goodName=orderGoodItemList.get(0).getGoodName()+"等"+orderGoodItemList.size()+"款商品信息";
						}
					}
					MemberAddress memberAddress=memberAddressMapper.selectByMemberIdAndId(member.getId(), orderGood.getAddressId());
					orderAddress=memberAddress.getCity()+memberAddress.getArea();
					orderProductPrice=orderGood.getGoodAmount();
			//		url=String.format("%s/"+groupId+"/shop_order_detail.html?orderId="+orderGood.getId(),masterUrl);
			 }else if(orderId.startsWith(Const.CONSUMPTION_VIRTUAL)){  
				 OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectOrderServiceGoodInfo(orderId,BizEnum.ServiceOrderStatus.OrderCancel.getType());
				 TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderId);
				 goodName = orderServiceGood.getGoodName();
				 orderAddress="无";
				 orderProductPrice=tradeOffline.getRealAmount();
			//	 url=String.format("%s/"+groupId+"/orderlist.html",masterUrl);
			 }else{
				 return false;
			 }
				templateMessage.setUrl(url);
				templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
				templateMessage.setToUser(member.getOpenid());
				templateMessage.getData().add(new WxMpTemplateData("first", "您的订单已取消。", "#000080"));
				double orderAmount = (double) (Math.round(orderProductPrice) / 100.0);
				templateMessage.getData().add(new WxMpTemplateData("orderProductPrice", orderAmount + "元", "#FF0000"));// 订单金额
				templateMessage.getData().add(new WxMpTemplateData("orderProductName", goodName, "#000080"));// 商品详情
				templateMessage.getData().add(new WxMpTemplateData("orderAddress", orderAddress, "#000080"));// 收货信息
				templateMessage.getData().add(new WxMpTemplateData("orderName", orderId, "#000080"));// 订单编号
				templateMessage.getData().add(new WxMpTemplateData("Remark", "\n点击详情可查看交易明细。", "#000080"));
				wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
				return true;
		}else if (BizEnum.WebTemplateType.template10.getType().equals(template)) {// 订单发货通知
					String goodName=null;
					OrderGood orderGood=orderGoodMapper.selectOrderGoodInfo(orderId, BizEnum.MallOrderStatus.WaitingForReceive.getType());
					if(orderGood!=null){
						List<OrderGoodItem> orderGoodItemList=orderGoodItemMapper.listByOrderId(orderGood.getId());
						if(orderGoodItemList.size()==1){
							goodName=orderGoodItemList.get(0).getGoodName();
						}else if(orderGoodItemList.size()>1){
							goodName=orderGoodItemList.get(0).getGoodName()+"等"+orderGoodItemList.size()+"商品信息";
						}
					}
					MemberAddress memberAddress=memberAddressMapper.selectByMemberIdAndId(member.getId(), orderGood.getAddressId());
					String orderAddress=memberAddress.getCity()+memberAddress.getArea();
//					String url=String.format("%s/"+groupId+"/shop_order_detail.html?orderId="+orderGood.getId(),masterUrl);
					String url=String.format("%s/"+member.getGroupId()+"/share_to.html?uid="+memberId,masterUrl);
					templateMessage.setUrl(url);
					templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
					templateMessage.setToUser(member.getOpenid());
					templateMessage.getData().add(new WxMpTemplateData("first", "嗖嗖嗖，您的订单已发货，我们正加速送到您的手上。", "#000080"));
					templateMessage.getData().add(new WxMpTemplateData("keyword1", goodName, "#000080"));
					templateMessage.getData().add(new WxMpTemplateData("keyword2", Tools.notEmpty(orderGood.getExpressName())?orderGood.getExpressName():"商家配送", "#000080"));
					templateMessage.getData().add(new WxMpTemplateData("keyword3", orderGood.getExpressNo().equals("-1")?null:orderGood.getExpressNo(), "#000080"));
					templateMessage.getData().add(new WxMpTemplateData("keyword4", orderAddress, "#000080"));// 收货信息
					templateMessage.getData().add(new WxMpTemplateData("remark", "请您耐心等候。", "#000080"));
					wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
				} 
		return false;
				
	}

	
	
	
	/**
	 * 查询用户余额
	 * 
	 * @param userId
	 * @param groupId
	 * @return
	 * @throws Exception
	 */
	private String queryAmount(String virtualCard, String payGroupCode,Long userId) throws Exception {
		Wallet wallet=walletService.selectwallet(virtualCard, payGroupCode, userId);
		Integer sum = wallet.getCanBalance()+wallet.getNocanBalance()+wallet.getCanFreezeBalance();
		return sum + "";
	}

	@Override
	@Async
	public Boolean sendTemplate(TradeOffline tradeOffline, String template,Long memberId, Long groupId, Integer businessType,String masterUrl, String status) throws Exception {
		GroupWxtemplate groupWxtemplate = groupWxtemplateMapper.selectByTemplateTypeAndGroup(template, groupId);
		System.out.println("----------------------------发送模板消息----------"+template);
		if (groupWxtemplate == null||StringUtils.isBlank(groupWxtemplate.getTemplateId())) {
			return false;
		}
		Member member = memberMapper.queryGroup(memberId);
		if(member==null){
			return false;
		}
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupId));

		String url=String.format("%s/"+groupId+"/share_to.html?uid="+memberId,masterUrl);

		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		if (BizEnum.WebTemplateType.template16.getType().equals(template)){//给洗衣机用的服务完成提醒
			MachineWasherLog machineWasherLog = new MachineWasherLog();
			machineWasherLog.setOrderno(tradeOffline.getOrderId());
			Map result = machineWasherLogMapper.selectWasherLogByOrderNo(machineWasherLog);
			templateMessage.setToUser(member.getOpenid());
			templateMessage.setTemplateId(groupWxtemplate.getTemplateId());
			templateMessage.setUrl(url);
			templateMessage.getData().add(new WxMpTemplateData("first", "亲，很高兴为您服务", "#000080"));
			templateMessage.getData().add(new WxMpTemplateData("keyword1", tradeOffline.getOrderId(), "#000080"));//订单号
			templateMessage.getData().add(new WxMpTemplateData("keyword2", "您选择了" + BizEnum.WashType.fromType(Integer.parseInt(result.get("washtype").toString())).getName() + "洗衣"));//服务项目
			templateMessage.getData().add(new WxMpTemplateData("keyword3", result.get("gmt_create").toString(), "#FF0000"));//开始服务时间
			templateMessage.getData().add(new WxMpTemplateData("keyword4", DateUtil.getTime(), "#000080"));// 完成服务时间
			templateMessage.getData().add(new WxMpTemplateData("remark", "\n您的洗衣已结束，请记得晾晒，欢迎再次使用!", "#000080"));
			wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			return true;
		}
		return false;
	}

}
